import Axios from "axios";
import {Message} from 'element-ui'

import config from '/config.js'

/**
 * 连接器
 */


let connector = {};

let token = config.token

function builder(baseUrl, isForm = false) {

    let axios = Axios.create();

    axios.interceptors.request.use(function (config) {
        if (config.method === 'post' && isForm) {
            config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
        }
        /*config.params = {
            token: token
        }
*/
        /*var isAuth = true;
        for (var i = 0; i < whiteList.length; i++) {
            if (config.url === whiteList[i]) {
                isAuth = false;
                break;
            }
        }
        if (isAuth) {
            let token = storage.getItem('token');
            if (token) config.headers['Token'] = token;
        }*/

        return config;
    }, function (err) {
        return Promise.reject(err);
    });

    // 响应拦截
    axios.interceptors.response.use(function (response) {

        /*if (response.data.code == 0) {
            return response.data;
        }
        if (response.data.code == "1") {
            Message.error(response.data.message)
        }
        if (response.data.code == '1010') {
            Message.error('没有权限！')
        }*/
        return response.data;
        //TODO 没有获取到数据提示  message 提示
    }, function (err) {
        // 后端服务没有响应结果，默认为服务关闭
        if (err.response) {
            return Promise.reject(err);
        } else {
            return Promise.reject({
                message: '后端服务已关闭'
            });
        }
    });
    return axios;
}


/**
 * 解析路径参数
 *
 * @param url
 * @param params
 * @returns {{url: string, params: *}}
 */
var resolvePath = function (url, params) {
    let result = null;
    if (params instanceof Array) {
        result = {url, params}
    } else {
        const pathParams = url.match(/\{\w+\}/g);
        let resolveUrl = '';
        if (pathParams && pathParams.length > 0) {
            for (var i = 0; i < pathParams.length; i++) {
                var param = pathParams[i];
                const key = param.match(/\w+/g)[0];
                if (key && params.hasOwnProperty(key)) {
                    if (resolveUrl) {
                        resolveUrl = resolveUrl.replace(param, params[key]);
                    } else {
                        resolveUrl = url.replace(param, params[key]);
                    }
                    delete params[key];
                }
            }
        }
        result = {url: resolveUrl || url, params: params};
    }
    return result;
};

/**
 * 查询
 *
 * @param   {string}  url
 * @param   {object}  params
 * @param   {string}  baseUrl+
 * @return  {promise}
 */
connector.query = function (url, params = {}, baseUrl = '') {
    var factory = builder(baseUrl);
    var resolve = resolvePath(url, params);
    return factory({
        method: 'get',
        url: resolve.url,
        params: resolve.params
    });
};
connector.getTags = function (url, params = {}, baseUrl = '') {
    var factory = builder(baseUrl);
    var resolve = resolvePath(url, params);
    return factory({
        method: 'get',
        url: resolve.url,
        params: resolve.params
    });
};

/**
 * 表单提交
 *
 * @param   {string}  url
 * @param   {object}  data
 * @param   {string}  baseUrl
 * @return  {promise}
 */
connector.post = function (url, data = {}, baseUrl = '', isForm = false) {
    var factory = builder(baseUrl, isForm);
    var resolve = resolvePath(url, data);
    return factory({
        method: 'post',
        url: resolve.url,
        data: resolve.params
    });
};

/***
 * 下载文件
 *
 * @param baseUrl
 * @param url
 * @param params
 * @param method
 * @param callback
 * @return {*}
 * @private
 */
connector.download = function (baseUrl, url, params, method, callback) {
    var factory = builder(baseUrl);
    var resolve = resolvePath(url, params);
    var config = {
        url: resolve.url,
        responseType: 'blob',
        onDownloadProgress: progressEvent => {
            if (typeof method === 'function') {
                method(progressEvent);
            } else {
                if (typeof callback === 'function') {
                    callback(progressEvent);
                }
            }
        }
    };
    if (typeof method === 'function') config.method = 'get';
    else config.method = method;
    if (config.method === 'post') config.data = resolve.params;
    else config.params = resolve.params;
    return factory(config);
};

/**
 * 上传文件
 *
 * @param url 地址
 * @param data 数据
 * @param callback 进度回调
 * @returns {Promise}
 */
connector.upload = function (url, data, callback) {
    var factory = builder();
    var resolve = resolvePath(url, data);
    return factory({
        url,
        data,
        method: 'post',
        headers: {'Content-Type': 'multiple/form-data'},
        onUploadProgress: function (progressEvent) {
            if (typeof callback === 'function') {
                callback(progressEvent);
            }
        }
    });
};

export default {
    connector
}

